import cv2
import os

def cv_imwrite(filename,src):
    cv2.imencode('.jpg',src)[1].tofile(filename)

def get_frame_from_video(video_name, frame_time, img_name):
    """
    get a specific frame of a video by time in milliseconds
    :param video_name: video name
    :param frame_time: time of the desired frame, (ms)
    :param img_name: name of output image
    :return: None
    """
    vidcap = cv2.VideoCapture(video_name)
    # Current position of the video file in milliseconds.
    vidcap.set(cv2.CAP_PROP_POS_MSEC, frame_time - 1)
    # read(): Grabs, decodes and returns the next video frame
    success, image = vidcap.read()

    if success:
        # save frame as JPEG file
        # cv2.imwrite(img_name, image)  
        cv_imwrite(img_name, image)  
        # cv2.imshow("frame%s" % frame_time, image)
        # cv2.waitKey()
    else:
        raise BaseException("[error] cv2 出错!")

if __name__ == "__main__":
    video_name = r"E:\Documents\备份\大三下\软件工程实践-刘峻\在线音乐及视频管理系统\1707310226-霍华骑-项目源代码\MVonline1-django\files\9a837d90d4714464a402db910eb38f9b.mp4"

    get_frame_from_video(video_name, 
    1000, 
    r"E:\Documents\备份\大三下\软件工程实践-刘峻\在线音乐及视频管理系统\1707310226-霍华骑-项目源代码\MVonline1-django\files\9a837d90d4714464a402db910eb38f9b.mp4.jpg")